import js from "@/app/financial/financialOutbound/js";
import {getSessionItem, setSessionItem} from "@/basa/utils";
import {listPageExwarehouseWriteOff, removeExwarehouseWriteOff, recallExwarehouseWriteOff} from "../api";
export default {
    data() {
        return {
            tabBtn: js.tabBtn,
            // 高级搜索
            formData: {},
            formDataSearch: {},
            // 表格数据
            tableData: [],
            tableHack: true,
            tableThead: [],
            tableName: this.getLabelType().tableName,
            // 动态表格
            tableTheadOptions: [],
            // 表格数据相关处理
            formatterList: {},
            // 分页
            totalNum: 0,
            pageNoCode: 1,
            pageSizeCode: this.getLocalPageSize(),
        }
    },
    methods: {
        // 初始换
        setInitData() {
            this.setTableWidth();
            this.renderTable();
        },

        // 高级搜索
        search(searchData) {
            this.pageNoCode = 1;
            if (searchData.reportTime && searchData.reportTime !== "") {
                searchData.reportTimeStart = new Date(searchData.reportTime[0]).getTime();
                searchData.reportTimeEnd = new Date(searchData.reportTime[1]).getTime();
                delete searchData.reportTime;
            }
            this.formDataSearch = JSON.parse(JSON.stringify(searchData));
            this.localSearchData = JSON.parse(JSON.stringify(searchData));
            setSessionItem("pageNo", this.tableName, {
                pageNo: this.pageNoCode,
                searchForm: this.localSearchData
            });
            this.getList(this.formDataSearch);
        },

        // 搜索切换
        change() {
            this.formData = {};
        },

        // 搜索重置
        resetForm() {
            this.formData = {};
            this.formDataSearch = {};
            this.getList(this.formDataSearch);
        },

        // tab切换
        tabChange(val) {
            this.$router.push({name: `financial_outBound_${val.value}`});
        },

        // 高级搜索去除空格
        handleTrim(key) {
            this.$set(this.formData, key, this.formData[key].replace(/(^\s*)|(\s*)$/g, ""));
        },

        // 新增跳转
        handleGoNew() {
            this.$router.push("/inventoryManagement/outBound/newItem");
        },

        // 编辑跳转
        handleGoEdit(row) {
            this.$router.push({
                path: "/inventoryManagement/outBound/newItem",
                query: {
                    id: row.id
                }
            });
        },

        // 行点击事件
        handleRowClick(row, column, event) {
            if (column.label == "冲销单编号") {
                this.$router.push({
                    path: "/inventoryManagement/outBound/detail",
                    query: {id: row.id}
                });
            }
        },

        // cellStyle 单元格样式
        cellStyle({columnIndex}) {
            if (columnIndex == 1) return {color: "#0089EF", cursor: "pointer"};
        },

        // 获取默认条数
        getLocalPageSize() {
            let pageBool = getSessionItem("pageSize", this.tableName);
            return pageBool ? getSessionItem("pageSize", this.tableName)[this.getLabelType().tableName] : 20
        },

        // 分页
        handlePrev() {
            // --this.pageNoCode;
            // this.getList(this.formDataSearch);
        },

        handleNext() {
            // ++this.pageNoCode;
            // this.getList(this.formDataSearch);
        },

        handleSizeChange(val) {
            console.log(this.tableName, '11');
            this.pageNoCode = 1;
            if (val !== "none") {
                this.pageSizeCode = val;
                setSessionItem("pageSize", this.tableName, val);
            }
            this.getList(this.formDataSearch);
        },

        handleCurrentChange(val) {
            let searchFormData = getSessionItem("pageNo", this.tableName) || {};
            setSessionItem("pageNo", this.tableName, {
                pageNo: val,
                searchForm: searchFormData.searchForm || {}
            });
            this.formDataSearch = {
                ...this.formDataSearch,
                ...searchFormData.searchForm
            };
            // 跳转翻页都会调这个方法
            this.pageNoCode = val;
            this.getList(this.formDataSearch);
        },

        // 删除
        handleDelete(row) {
            this.$confirm("您确定要删除吗？", "删除确认", {
                distinguishCancelAndClose: true,
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                customClass: "ccui-message-box-custom"
            }).then(() => {
                removeExwarehouseWriteOff({id: row.id, isShowLoading: true}).then(res => {
                    this.$message({
                        type: "success",
                        message: res.data.message,
                        duration: 800,
                        onClose: () => {
                            this.getList(this.formDataSearch);
                        }
                    });
                });
            });
        },

        // 撤回
        getRevoke(row) {
            this.$confirm("您确定要撤回吗？", "撤回确认", {
                distinguishCancelAndClose: true,
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                customClass: "ccui-message-box-custom"
            }).then(() => {
                recallExwarehouseWriteOff({id: row.id, isShowLoading: true}).then(res => {
                    this.$message({
                        type: "success",
                        message: res.data.message,
                        duration: 800,
                        onClose: () => {
                            this.getList(this.formDataSearch);
                        }
                    });
                });
            });
        },

        // 列表数据
        getList(obj) {
            obj.labelType = this.getLabelType().status;
            obj.pageNo = this.pageNoCode;
            obj.pageSize = this.pageSizeCode;
            obj.isShowLoading = true;

            listPageExwarehouseWriteOff(obj).then(res => {
                let result = res.data.data;
                result.rows.map(e => {
                    e.exwarehouseStatus = js.exwStatus[e.exwarehouseStatus];
                    e.reportTime = e.reportTime ? e.reportTime.substr(0, 10) : "";
                    e.exwarehouseCount = e.exwarehouseCount? (0 - Math.abs(e.exwarehouseCount)).toFixed(3) : "";
                    e.exwarehouseMoney = e.exwarehouseMoney? (0 - Math.abs(e.exwarehouseMoney)).toFixed(2) : "";
                });
                this.totalNum = result.recordsTotal;
                this.pageNoCode = result.pageNo;
                this.tableData = result.rows;
            });
        },

        getLabelType() {
            let obj = {
                status: 0,
                tableName: ""
            };
            let route = this.$route.name;
            if (route.endsWith("all")) {
                obj.status = 0;
                obj.tableName = this.tableList.financialOutboundAll;
            } else if (route.endsWith("toSubmit")) {
                obj.status = 1;
                obj.tableName = this.tableList.financialOutboundToSubmit;
            } else if (route.endsWith("approval")) {
                obj.status = 2;
                obj.tableName = this.tableList.financialOutboundApproval;
            } else if (route.endsWith("takeBack")) {
                obj.status = 3;
                obj.tableName = this.tableList.financialOutboundTakeBack
            }
            return obj;
        },

        // 默认渲染表格
        renderTable() {
            const localTableData = localStorage.getItem(this.tableName)
                ? JSON.parse(localStorage.getItem(this.tableName))
                : [];
            let unfixedTableThead = js.unfixedTableThead.concat(
                js.fixedTableThead
            );
            let localTableDataStr = localTableData.map(
                ({label, prop, formatter, align}) =>
                    JSON.stringify({label, prop, formatter, align})
            );
            let unfixedTableTheadStr = unfixedTableThead.map(
                ({label, prop, formatter, align}) =>
                    JSON.stringify({label, prop, formatter, align})
            );

            if (localTableData.length === unfixedTableThead.length) {
                let flag = localTableDataStr.every(item =>
                    unfixedTableTheadStr.includes(item)
                );
                if (flag) {
                    // 完全相同
                    this.tableTheadOptions = localTableData;
                    this.tableThead = localTableData;
                    js.unfixedTableThead = localTableData.filter(item => {
                        return !js.fixedTableThead.find(
                            cItem => item.prop === cItem.prop
                        );
                    });
                } else {
                    // 长度相同但值不同
                    this.tableThead = js.unfixedTableThead.concat(js.fixedTableThead);
                    const comment = JSON.stringify(this.tableThead);
                    localStorage.setItem(this.tableName, comment);
                    const localTableData = JSON.parse(
                        localStorage.getItem(this.tableName)
                    );
                    this.tableTheadOptions = localTableData;
                }
            } else {
                // 长度不同
                this.tableThead = js.unfixedTableThead.concat(js.fixedTableThead);
                const comment = JSON.stringify(this.tableThead);
                localStorage.setItem(this.tableName, comment);
                const localTableData = JSON.parse(localStorage.getItem(this.tableName));
                this.tableTheadOptions = localTableData;
            }
        },

        // 渲染本地存储表格宽度
        setTableWidth() {
            const localTableData = JSON.parse(localStorage.getItem(this.tableName));
            if (localTableData) {
                for (let i = 0; i < this.tableTheadOptions.length; i++) {
                    if (this.tableTheadOptions[i].label === localTableData[i].label) {
                        this.tableTheadOptions[i].width = localTableData[i].width;
                    }
                }
            }
        },

        // 表格宽度更改存入
        setTableTitleWidth(newWidth, oldWidth, column, event) {
            for (let i = 0; i < js.unfixedTableThead.length; i++) {
                if (js.unfixedTableThead[i].label === column.label) {
                    js.unfixedTableThead[i].width = newWidth;
                }
            }
            this.tableThead = js.unfixedTableThead.concat(js.fixedTableThead);
            const comment = JSON.stringify(this.tableThead);
            localStorage.setItem(this.tableName, comment);
            this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
            this.tableHack = false;
            this.$nextTick(() => {
                this.tableHack = true;
            });
        },
    },
    mounted() {
        this.setInitData();
    },
    activated() {
        this.getList(this.formDataSearch);
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            switch (to.path) {
                case "/inventoryManagement/outBound/all" :
                    vm.$refs.tableListAll.doLayout();
                    break;
                case "/inventoryManagement/outBound/toSubmit" :
                    vm.$refs.tableListToSubmit.doLayout();
                    break;
                case "/inventoryManagement/outBound/approval" :
                    vm.$refs.tableListApproval.doLayout();
                    break;
                case "/inventoryManagement/outBound/takeBack" :
                    vm.$refs.tableListTakeBack.doLayout();
                    break;
            }
        });
    }
}